﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;
using PMSGSC.DAL;
using System.Data.Linq;
using PMSGSC.BLL;

namespace PMSGSC.App.Sys
{
    public partial class frmInFor : DevExpress.XtraEditors.XtraForm
    {
        public frmInFor()
        {
            InitializeComponent();
            shipBindingSource.Add(frmMain.ship);
            pictureEdit1.EditValue = frmMain.ship.Image.ToArray();
            ship = shipBindingSource.Current as Ship;
        }
        Ship ship;
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            return ms.ToArray();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            byte[] b = imageToByteArray(pictureEdit1.Image);
            ship.Image = b;
            Ship_BLL.Update(ship);
            XtraMessageBox.Show("Update Ship's information successly !", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }

        private byte[] StreamFile(string fileName)
        {
            // Open file
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            // ByteArray
            byte[] ImageData = new byte[fs.Length];

            // Read block of bytes
            fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));

            // Close it
            fs.Close();

            // Return the byte data
            return ImageData;
        }

        public bool ByteArrayToFile(string fileName, byte[] byteArray)
        {
            try
            {
                // Open file for reading
                System.IO.FileStream fileStream = new System.IO.FileStream
                    (fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                // Writes a block of bytes
                fileStream.Write(byteArray, 0, byteArray.Length);

                // Close file stream
                fileStream.Close();

                return true;
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.ToString());
            }
            return false;
        }
    }
}